package com.huxiu.yd;

import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.Utils;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/8/18:下午6:32.
 */
public class RegisterActivity extends AuthenticatorActivity implements OnClickListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.username_edit)
    EditText usernameEdit;

    @InjectView(R.id.verify_code)
    EditText verifyCodeEdit;

    @InjectView(R.id.get_verify_code_button)
    TextView getVerifyCodeButton;

    @InjectView(R.id.forget_password)
    TextView forgetPassword;

    @InjectView(R.id.log_in_button)
    Button logInButton;

    @InjectView(R.id.weibo_log_in)
    ImageView weiboLogIn;

    @InjectView(R.id.qq_log_in)
    ImageView qqLogIn;

    @InjectView(R.id.weixin_log_in)
    ImageView weixinLogIn;

    @InjectView(R.id.huxiu_log_in)
    ImageView huxiuLogIn;

    @InjectView(R.id.oauth_log_in_layout)
    LinearLayout oauthLogInLayout;

    @InjectView(R.id.oauth_hint)
    TextView oauthHint;

    private static final int VERIFY_CODE_TIMEOUT = 60;

    private boolean isFindPassword = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        isFindPassword = getIntent().getBooleanExtra("forget_password", false);
        ButterKnife.inject(this);
        back.setOnClickListener(this);
        if (isFindPassword) {
            title.setText(R.string.find_password);
        } else {
            title.setText(R.string.register);
        }
        rightImage.setVisibility(View.GONE);
        logInButton.setOnClickListener(this);
        getVerifyCodeButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.log_in_button:
                if (TextUtils.isEmpty(usernameEdit.getText().toString())) {
                    Utils.showToast(R.string.pls_input_mobile);
                } else if (TextUtils.isEmpty(verifyCodeEdit.getText().toString())) {
                    Utils.showToast(R.string.pls_input_verify_code);
                } else {
                    verify();
                }
                break;
            case R.id.get_verify_code_button:
                if (TextUtils.isEmpty(usernameEdit.getText().toString())) {
                    Utils.showToast(R.string.pls_input_mobile);
                } else {
                    getVerifyCode();
                }
                break;
        }
    }

    private void launchNextScreen() {
        Intent intent = new Intent(this, RegisterActivity2.class);
        intent.putExtra(Constants.MOBILE_KEY, usernameEdit.getText().toString());
        intent.putExtra(Constants.VERIFY_CODE_KEY, verifyCodeEdit.getText().toString());
        intent.putExtra("forget_password", isFindPassword);
        startActivityForResult(intent, 0);
    }

    private void cleanHandler() {
        try {
            handler.sendEmptyMessage(MSG_COUNT_DOWN_FINISHED);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final int MSG_COUNT_DOWN = 30;

    private static final int MSG_COUNT_DOWN_BEGIN = 31;

    private static final int MSG_COUNT_DOWN_FINISHED = 32;

    private int countDown = VERIFY_CODE_TIMEOUT;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_COUNT_DOWN_BEGIN:
                    getVerifyCodeButton.setEnabled(false);
                    sendEmptyMessage(MSG_COUNT_DOWN);
                    break;
                case MSG_COUNT_DOWN:
                    countDown--;
                    getVerifyCodeButton.setText(countDown + "秒");
                    if (countDown > 0) {
                        sendEmptyMessageDelayed(MSG_COUNT_DOWN, 1000);
                    } else {
                        sendEmptyMessage(MSG_COUNT_DOWN_FINISHED);
                    }
                    break;
                case MSG_COUNT_DOWN_FINISHED:
                    removeMessages(MSG_COUNT_DOWN);
                    if (TextUtils.isEmpty(verifyCodeEdit.getText().toString())) {
                        getVerifyCodeButton.setText(R.string.get_verify_code_again);
                        getVerifyCodeButton.setEnabled(true);
                    }
                    countDown = VERIFY_CODE_TIMEOUT;
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        finishCountdown();
        super.onDestroy();
    }

    private void finishCountdown() {
        countDown = 0;
        handler.removeMessages(MSG_COUNT_DOWN);
    }

    private void getVerifyCode() {
        handler.sendEmptyMessage(MSG_COUNT_DOWN_BEGIN);
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", usernameEdit.getText().toString());
//        params.put("captcha", verifyCodeEdit.getText().toString());
        params.put("act", "send_mobile_msg");
        GsonRequest<BaseResponse> request = new GsonRequest<>(NetworkConstants.MEMBER_URL,
                Method.POST, BaseResponse.class, false, params, new Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissProgress();
                if (response.isSuccess()) {
                    Utils.showToast(R.string.get_verify_code_success);
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
        showProgress();
    }

    private void verify() {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("mobile", usernameEdit.getText().toString());
        params.put("captcha", verifyCodeEdit.getText().toString());
        params.put("act", "check_captcha");
        GsonRequest<BaseResponse> request = new GsonRequest<>(NetworkConstants.MEMBER_URL,
                Method.POST, BaseResponse.class, false, params, new Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissProgress();
                if (response.isSuccess()) {
                    launchNextScreen();
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
        showProgress();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 0:
                setResult(RESULT_OK);
                finish();
                break;
        }
    }
}
